package com.jrzh.listener.sys;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.jrzh.common.utils.DateUtil;
import com.jrzh.config.ProjectConfigration;
import com.jrzh.db.data.execute.sys.ExecuteConfig;
import com.jrzh.db.data.execute.sys.ExecuteI18n;
import com.jrzh.db.data.execute.sys.ExecuteInitData;
import com.jrzh.db.data.execute.sys.ExecuteSysResources;
import com.jrzh.framework.migration.MigrationHelper;
import com.jrzh.mvc.constants.SysConstant;
import com.jrzh.mvc.service.sys.ConfigServiceI;
import com.jrzh.mvc.service.sys.I18nServiceI;

@Component("sysStartUpListener")
@Order(1)
public class SysStartUpListener implements ApplicationListener<ContextRefreshedEvent>{
	
	Log log = LogFactory.getLog(getClass());
	
	@Autowired
	private ProjectConfigration projectConfigration;
	
	@Resource(name = "configService")
	private ConfigServiceI configService;
	
	@Resource(name = "i18nService")
	private I18nServiceI i18nService;
	
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if(event.getApplicationContext().getParent() == null){
			log.info(DateUtil.getMark() + "系统模块启动事件触发.......");
			SysConstant.MODULE_LIST.add(SysConstant.MODULE_NAME);
			executeDataBase();
			executeDbData(event.getApplicationContext());
			initCacheData();
		}
	}
	/**
	 * 执行数据库脚本
	 */
	private void executeDataBase(){
		MigrationHelper.updateDataBase(projectConfigration, "sys");
	}
	
	private void executeDbData(ApplicationContext context){
		new ExecuteSysResources().execute(context);
		new ExecuteInitData().execute(context);
		new ExecuteConfig().execute(context);
		new ExecuteI18n().execute(context);
	}
	/**
	 * 初始化缓存数据
	 */
	private void initCacheData(){
		try {
			configService.initCache();
			i18nService.initCache();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
